package com.zhuang.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuang.reggie.common.CustomException;
import com.zhuang.reggie.entity.Category;
import com.zhuang.reggie.entity.Dish;
import com.zhuang.reggie.entity.Setmeal;
import com.zhuang.reggie.mapper.CategoryMapper;
import com.zhuang.reggie.service.CategoryService;
import com.zhuang.reggie.service.DishService;
import com.zhuang.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类，删除之前需要进行判断该分类是否已经关联了菜品和套餐，如果已经关联则不能删除
     *
     * @param id
     */
    @Override
    public void remove(Long id) {

        //1.查询当前分类是否关联了菜品，如果已经关联，抛出一个业务异常
        LambdaQueryWrapper<Dish> dishlambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据菜品分类id进行查询
        dishlambdaQueryWrapper.eq(Dish::getCategoryId, id);
        //查询数量
        long countByDish = dishService.count(dishlambdaQueryWrapper);
        if (countByDish>0) {
            //要删除的分类已经关联菜品，抛出一个业务异常
            throw new CustomException("当前分类下关联了菜品，无法删除！");
        }

        //2.查询当前分类是否关联了套餐，如果已经关联，抛出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据套餐分类id进行查询
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        //查询数量
        long countBySetmeal = setmealService.count(setmealLambdaQueryWrapper);
        if (countBySetmeal>0) {
            //要删除的分类已经关联套餐，抛出一个业务异常
            throw new CustomException("当前分类下关联了套餐，无法删除！");
        }

        //3.正常删除分类
        super.removeById(id);//因为继承了ServiceImpl，所以要调用ServiceImpl里面的方法要使用super
    }
}
